package cn.fzkj.framework.security.service;

import cn.fzkj.common.ResultCode;
import cn.fzkj.common.ResultVO;
import cn.fzkj.common.constant.Constants;
import cn.fzkj.framework.exception.client.ClientException;
import cn.fzkj.framework.redis.utils.RedisUtil;
import cn.fzkj.framework.security.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class LoginService {
    private static final Logger log = LoggerFactory.getLogger(LoginService.class);

    @Autowired
    private TokenService tokenService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * @param username 登录用户名
     * @param password 登录密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return
     */
    public ResultVO login(String username, String password, String code, String uuid){
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisUtil.getCacheObject(verifyKey);
        //redisUtil.del(verifyKey); // 上线之后取消注释，点击一次登录之后验证码就失效了
        if (captcha == null){
           // 验证码不存在，【失效】
            return ResultVO.failure(ResultCode.CODE_EXPIRE);
        }if (!code.equalsIgnoreCase(captcha)){
            // 验证码错误
            return ResultVO.failure(ResultCode.CODE_ERROR);
        }

        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                throw new ClientException("");
            }
            else
            {
                log.error("LoginService 抛出异常");
                throw new ClientException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        String token = tokenService.createToken(loginUser);
        Map map = new HashMap<>();
        map.put("token", token);
        return ResultVO.success(map);
    }
}
